'''
1.迭代器使用
    迭代器是实现迭代器协议的对象，它包含方法 __iter__() 和 __next__()。
2.生成器使用
    通过yield生成迭代器，通过next()方法迭代出来

'''

# 列表、元组、字典和集合都是可迭代的对象。它们是可迭代的容器，您可以从中获取迭代器（Iterator）。所有这些对象都有用于获取迭代器的 iter() 方法：
import sys


def tuple_iter():
    arr = ("hello", "world", "hello", "python")
    print(id(arr))
    print(type(arr))
    iter_arr = iter(arr)
    print(iter_arr)
    print(type(iter_arr))
    print(id(iter_arr))
    '''
    效果等于下面
    for iter_next in iter_arr:
       print(iter_next)
    '''
    print(next(iter_arr))
    print(next(iter_arr))
    print(next(iter_arr))
    print(next(iter_arr))
    # for iter_next in iter_arr:
    #     print(iter_next)


class Person:
    def __iter__(self):
        self.age = 1
        return self

    def __next__(self):
        if self.age <= 120:
            current_age = self.age
            self.age += 1
            return current_age
        else:
            # raise StopIteration，运用于迭代器中，执行这段代码，就会自动推出循环
            raise StopIteration


# 通过yield实现斐波那契数列
def fibonacci(n):
    a, b, counter = 0, 1, 0
    while True:
        if counter > n:
            return
        yield a
        counter += 1
        a, b = b, a + b  # a=0,b=1,---> a=1,b=0+1=1---->a=1,b=1+1=2---->a=2,b=1+2=3.............


def generate_iterator(n):
    f = fibonacci(n)
    print(type(f))
    print(f)
    print("*" * 100)
    while True:
        try:
            print(next(f), end=" ")
        except StopIteration:
            sys.exit()


if __name__ == '__main__':
    tuple_iter()
    iter_num = fibonacci(10)
    p = Person()
    p_iter = iter(p)
    for p_age in p_iter:
        print(p_age, end="\t")
    generate_iterator(110)

    # print(type(iter_num))
    # print(iter_num)
